package com.yngrp.service.impl.wo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yngrp.entity.Group2CustomerNo;
import com.yngrp.entity.GroupInfo;
import com.yngrp.entity.TaskCustomerNoDetail;
import com.yngrp.entity.TaskElecQuery;
import com.yngrp.entity.TaskGroupDetail;
import com.yngrp.service.wo.GroupPowerRateService;
import com.yngrp.util.Constant;

/**
 *  @Description: 集团电费查询业务接口实现类
 *  @author  SLH
 *  @date  20160810
 *
 */

@Service("groupRateService")
@Transactional
public class GroupPowerRateServiceImpl extends CommonServiceImpl implements GroupPowerRateService {
	
	/**
	 * 新增集团
	 * @param gi
	 */	
	@Override
	public void saveGroup(GroupInfo gi) {
		// TODO Auto-generated method stub
		gi.setQueryModeDesc(getNameByTypeCode(Constant.AP_QUERYMODE,gi.getQueryMode()));
		gi.setStateDesc(getNameByTypeCode(Constant.GROUP_STATE,gi.getState()));
		if(gi.getId()!=null){
			gi.setActiveStateDesc(getNameByTypeCode(Constant.GROUP_ACTIVE_STATE,gi.getActiveState()));			
		}else{
			gi.setActiveState(Constant.GROUP_ENABLE_ACTIVE_STATE);
			gi.setActiveStateDesc(getNameByTypeCode(Constant.GROUP_ACTIVE_STATE,Constant.GROUP_ENABLE_ACTIVE_STATE));
		}
		
		TSUser user = ResourceUtil.getSessionUserName();
		
		gi.setCreateBy(user.getId());
		gi.setCreateRealname(user.getRealName());
		gi.setCreateDepartmentid(user.getCurrentDepart().getId());
		gi.setCreateDepartmentname(user.getCurrentDepart().getDepartname());
		gi.setCreateDatetime(new Date());
		
		this.commonDao.saveOrUpdate(gi);
	}
	
	/**
	 * 新增集团户号
	 * @param gc
	 */
	@Override
	public void saveCustomerNo(Group2CustomerNo gc){
		if(StringUtils.isEmpty(gc.getId())){
			gc.setId(null);
		} 
		gc.setQueryModeDesc(getNameByTypeCode(Constant.AP_QUERYMODE,gc.getQueryMode()));
		this.commonDao.saveOrUpdate(gc);
	}
	

	/**
	 * 删除查询任务信息
	 * @param aqa
	 */
	public void deleteQueryTask(TaskElecQuery teq){
		this.commonDao.executeHql("delete from TaskGroupDetail where queryTask.id = "+teq.getId());
    	this.commonDao.executeHql("delete from TaskCustomerNoDetail where queryTask.id = "+teq.getId());
    	
    	teq = this.commonDao.getEntity(TaskElecQuery.class, teq.getId());
		this.commonDao.delete(teq);
	}
	
	/**
	 * 删除查询任务集团
	 * @param tgd
	 */
	public void deleteTaskGroup(TaskGroupDetail tgd){		
    	this.commonDao.executeHql("delete from TaskCustomerNoDetail where queryTask.id = "+tgd.getQueryTask().getId()+" and groupInfo.id = "+tgd.getGroupInfo().getId());
    	this.commonDao.delete(tgd);
	}
	
	/**
	 * 完成任务
	 * @param teq
	 */
	public void finishTask(TaskElecQuery teq){
		List<TaskGroupDetail> tgdLst = this.commonDao.findHql("from TaskGroupDetail where queryTask.id = ?",teq.getId());
		GroupInfo groupInfo = null;
		for(TaskGroupDetail tgd:tgdLst){
			groupInfo = tgd.getGroupInfo();
			
			//激活集团
			groupInfo.setActiveState(Constant.GROUP_ENABLE_ACTIVE_STATE);
			groupInfo.setActiveStateDesc(getNameByTypeCode(Constant.GROUP_ACTIVE_STATE,Constant.GROUP_ENABLE_ACTIVE_STATE));
			this.commonDao.saveOrUpdate(groupInfo);
		}
		
		//更新任务状态为已完成
		teq = this.commonDao.getEntity(TaskElecQuery.class, teq.getId());
		teq.setState(Constant.AP_1_STATE);
		teq.setStateDesc(Constant.AP_1_STATE_DESC);
		this.commonDao.saveOrUpdate(teq);
	}
	
	/**
	 * 通过cq获取全部实体
	 * 
	 * @param <T>
	 * @param cq
	 * @return
	 */
	public <T> List<T> getListByCriteriaQuery(final CriteriaQuery cq,
			Boolean ispage) {
		return commonDao.getListByCriteriaQuery(cq, ispage);
	}
	
	/**
	 * 生成查询任务
	 * @param queryStartDate  开始日期
	 * @param queryEndDate  结束日期
	 * @param createMode  生成方式
	 */
	public String createQueryTask(String queryStartDate,String queryEndDay,String createMode){
		long subDay = Constant.getDaySub(queryStartDate, queryEndDay);

		GregorianCalendar gc=new GregorianCalendar();
		String queryDay = queryStartDate;
		for(long i=0;i<=subDay;i++){
			try {
				gc.setTime(new SimpleDateFormat(Constant.FORMART_QUERY_DAY).parse(queryStartDate));
				gc.add(5, (int)i);				
				queryDay = new SimpleDateFormat(Constant.FORMART_QUERY_DAY).format(gc.getTime());

				createQueryTask(queryDay, Constant.MANUAL_CREATE_MODE);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return Constant.ERROR;
			}
	         
		}
				
		return Constant.SUCCESS;
	}
	
	
	/**
	 * 生成查询任务
	 * @param queryDate  查询日期
	 * @param createMode  生成方式
	 */
	public String createQueryTask(String queryDate,String createMode){
		//如果查询任务未完成，则直接退出
		if(checkQueryTask(queryDate)){
			return Constant.SUCCESS;
		}
		
		//查询日期转Date对象
		Date qDate = null;	
		//查询方式
		String querymode = "";
		try {
			 qDate = DateUtils.parseDate(queryDate, Constant.FORMART_QUERY_DAY);
			 Calendar calendar=Calendar.getInstance();
			 calendar.setTime(qDate);			 
			 int month=calendar.get(Calendar.MONTH)+1;
			 int day=calendar.get(Calendar.DAY_OF_MONTH);
			 if(month%2==0){
				 querymode = Constant.EVEN_MONTH;
			 }else{
				 querymode = Constant.ODD_MONTH;
			 }
			 
			 //查询符合生成条件的集团
			 List<GroupInfo> groupLst = this.commonDao.findHql("from GroupInfo where (queryMode='"+Constant.EVERY_MONTH+"' or queryMode = ? ) and queryDate = ? and state ='"+Constant.GROUP_ENABLE_STATE+"'",querymode,day);
			 if(groupLst==null || groupLst.size()==0){
				 return Constant.NONE;
			 }
			 
			 TaskElecQuery teq = new TaskElecQuery();
			 teq.setQueryDate(queryDate);
			 teq.setGroupNum(groupLst.size());
			 teq.setCreateMode(createMode);
			 teq.setState(Constant.AP_0_STATE);
			 teq.setStateDesc(Constant.AP_0_STATE_DESC);
			 teq.setCreateDatetime(new Date());
			 //保存查询任务集团及户号信息
			 saveQueryTask(teq,groupLst);
	 
		} catch (ParseException e) {
			 // TODO Auto-generated catch block
			 e.printStackTrace();
			 return Constant.ERROR;
		}
		
		 return Constant.SUCCESS;
	}
	
	/**
	 * 保存查询任务集团及户号信息
	 * @param teq
	 * @param groupLst
	 */
	private void saveQueryTask(TaskElecQuery teq,List<GroupInfo> groupLst){
		
        //保存电费查询任务
        this.commonDao.save(teq);
 
        for(GroupInfo group:groupLst){
        	TaskGroupDetail tgd = new TaskGroupDetail();
        	tgd.setQueryTask(teq);
        	
        	if(group!=null){
        		//获取集团下所有户号
	        	List<Group2CustomerNo> gcnLst = this.commonDao.findHql("from Group2CustomerNo where groupInfo.id = ? ", group.getId());
	        	
	        	GroupInfo gi = this.commonDao.get(GroupInfo.class, group.getId());
	        	tgd.setGroupInfo(gi);
	        	tgd.setTotalNum(gcnLst.size());
	        	//保存集团用户信息
	        	this.commonDao.save(tgd);	        	
	        	
	        	for(Group2CustomerNo gcn:gcnLst){
	        		TaskCustomerNoDetail tcnd = new TaskCustomerNoDetail();
	        		tcnd.setQueryTask(teq);
	        		tcnd.setGroupInfo(gi);
	        		tcnd.setCustomerNo(gcn.getCustomerNo());
	        		tcnd.setQueryMode(gcn.getQueryMode());
	        		tcnd.setQueryModeDesc(gcn.getQueryModeDesc());
	        		//保存集团户号信息
	        		this.commonDao.save(tcnd);
	        	}
	        	
	        	//锁定集团
	        	gi.setActiveState(Constant.GROUP_DISABLE_ACTIVE_STATE);
				gi.setActiveStateDesc(getNameByTypeCode(Constant.GROUP_ACTIVE_STATE,Constant.GROUP_DISABLE_ACTIVE_STATE));
				this.commonDao.saveOrUpdate(gi);
        	}
        }    
	}
	
	/**
	 * 验证未完成查询任务
	 * @param queryDate  查询日期
	 */
	public boolean checkQueryTask(String queryDate){
		List<TaskElecQuery> taskLst = this.commonDao.findHql("from TaskElecQuery where queryDate = ? and state ='"+Constant.AP_0_STATE+"'", queryDate);
		if(taskLst!= null && taskLst.size()>0){
			return true;
		}
		return false;
	}
	
	/**
	 * 根据字典描述获取字典项编码
	 * @param typeGroupCode
	 * @param woTypeCode
	 * @return
	 */
	public String getCodeByName(String typeGroupCode,String woTypeName){
		return this.getCodeByTypeName(typeGroupCode, woTypeName);
	}
	
}